<?php
/*
 * @author Carlos Roberto Alvarez Muñoz <ingcram@gmail.com>
 */
Load::lib('libsubir');
class Banners extends ActiveRecord
{
    const INACTIVO  =   0;
    const ACTIVO    =   1;
    const DIR = "/public/img/upload/banners";
    const DIR_BD = "upload/banners/";
    public $debug = FALSE;
    
    public function guardar()
    {        
        $file = Upload::factory('archivo','image');   
        if($file->isUploaded()) 
        {	                    
            $file->setMaxSize('2MB');// Tamaño máximo
            // Tipos de archivos permitidos
            //$file->setTypes(array('image/jpeg'));            
            // Extensiones permitidas
            //$file->setExtensions(array('jpg'));           
            $fileName = $_FILES["archivo"]["name"]; 
            Flash::notice($fileName);
            $fileName = md5(time()).".".getExtensionFile($fileName);
            Flash::notice($fileName);
            $ruta = dirname(APP_PATH).Banners::DIR;           
            $file->setPath($ruta);
            
            if($file->save($fileName))
            {
                Flash::notice('hasta aqui');
                if(!is_bool($fileName))
                {                 
                    $this->tamanio = $_FILES["archivo"]["size"];    	 	
                    $this->nombre = $fileName;
                    $this->ruta = Banners::DIR_BD.$fileName;     	 	
                    $this->titulo = $_POST['banners']['titulo'];
                    $this->descripcion = $_POST['banners']['descripcion'];
                    $this->estatus = 0;

                    if($this->save())
                    {                            
                            return TRUE;
                    }
                }
            } 
        }               
    }    		    
    
    public function getAll($page, $ppage=20)
    {
        return $this->paginate("page: $page", "per_page: $ppage",  'order: id desc');        
    }
    
    public function getByActivo()
    {
        return $this->find_first(" estatus = ".Banners::ACTIVO);        
    }
    
    public function getBanner($banner_id)
    {
        return $this->find_first($banner_id);        
    }
    
    public function actualizar($banner)
    {
        return $this->update($banner);       
    }
    
    public function borrar($banner_id)
    {
        $this->getBanner($banner_id);
        
        if(file_exists(dirname(APP_PATH)."".Banners::DIR."/".$this->nombre)){
            Flash::notice(dirname(APP_PATH)."".Banners::DIR."/".$this->nombre);
            //chmod(dirname(APP_PATH)."".Banners::DIR."/".$this->name,0777);
            if( unlink(dirname(APP_PATH)."".Banners::DIR."/".$this->nombre)   ){
                
                return $this->delete($banner_id);
            }
        }
        
        
                        
        
    }

}
